package com.doufen.gateway;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.doufen.common.result.Result;
import com.doufen.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.DataBuffer;
import java.nio.charset.StandardCharsets;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        // 放行登录 & 短信
        if (path.contains("/base/login") || path.contains("/base/sms")) {
            return chain.filter(exchange);
        }

        String token = getToken(exchange);
        if (StrUtil.isBlank(token)) {
            return unauthorized(exchange, "Token 缺失");
        }
        try {
            Claims claims = JwtUtil.parseToken(token);
            // 把头信息传给下游
            ServerWebExchange mutate = exchange.mutate()
                    .request(r -> r.header("x-user-id", claims.getSubject())
                            .header("x-user-type", (String) claims.get("userType")))
                    .build();
            return chain.filter(mutate);
        } catch (Exception e) {
            return unauthorized(exchange, "Token 非法");
        }
    }

    private Mono<Void> unauthorized(ServerWebExchange exchange, String msg) {
        ServerHttpResponse resp = exchange.getResponse();
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        Result<Void> result = Result.fail(401, msg);
        DataBuffer buffer = resp.bufferFactory().wrap(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Mono.just(buffer));
    }

    private String getToken(ServerWebExchange exchange) {
        String bearer = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StrUtil.startWith(bearer, "Bearer ")) {
            return bearer.substring(7);
        }
        return null;
    }

    @Override
    public int getOrder() {
        return -100; // 最先执行
    }
}
